﻿#include "RenderTexture2D.h"

/////////////////////////////////////////////////////
// URenderTexture2D

URenderTexture2D::URenderTexture2D(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	AddressX = ERenderTextureAddressMode::TA_Wrap;
	AddressY = ERenderTextureAddressMode::TA_Wrap;
	Filter = ERenderTextureFilter::TF_Nearest;
	bSRGB = false;
}

FLinearColor URenderTexture2D::Sample(float U, float V)
{
	float RealU = U;
	
	if (AddressX == ERenderTextureAddressMode::TA_Wrap)
	{
		// 环绕模式
		// 获取小数部分
		RealU = U - FMath::FloorToInt(U);
	}
	else if (AddressX == ERenderTextureAddressMode::TA_Clamp)
	{
		// 限制模式
		RealU = FMath::Clamp(U, 0.0f, 1.0f);
	}
	else if (AddressX == ERenderTextureAddressMode::TA_Mirror)
	{
		// 镜像模式
		// 获取小数部分
		RealU = U - FMath::FloorToInt(U);

		if (FMath::FloorToInt(U) % 2 == 1)
		{
			RealU = 1 - RealU;
		}
	}

	float RealV = V;

	if (AddressY == ERenderTextureAddressMode::TA_Wrap)
	{
		// 获取小数部分
		RealV = V - FMath::FloorToInt(V);
	}
	else if (AddressY == ERenderTextureAddressMode::TA_Clamp)
	{
		RealV = FMath::Clamp(V, 0.0f, 1.0f);
	}
	else if (AddressY == ERenderTextureAddressMode::TA_Mirror)
	{
		// 获取小数部分
		RealV = V - FMath::FloorToInt(V);

		if (FMath::FloorToInt(V) % 2 == 1)
		{
			RealV = 1 - RealV;
		}
	}

	// TODO 双线性差值  三线性差值
	
	// 最近点采样
	const int32 Column = static_cast<int32>((Mips[0].SizeX - 1) * RealU);
	const int32 Row = static_cast<int32>((Mips[0].SizeY - 1) * RealV);
	const uint8* ColorData = &Mips[0].TextureData[(Row * Mips[0].SizeX + Column) * 4];

	float R = ColorData[2] / 255.0f;
	float G = ColorData[1] / 255.0f;
	float B = ColorData[0] / 255.0f;
	float A = ColorData[3] / 255.0f;
	
	if (bSRGB)
	{
		R = FMath::Pow(R, 2.2f);
		G = FMath::Pow(G, 2.2f);
		B = FMath::Pow(B, 2.2f);
	}

	
	
	return FLinearColor(R, G, B, A);
}

/////////////////////////////////////////////////////

